package com.bbcare.department.plat.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.bbcare.comm.AppException;
import com.bbcare.comm.Constants;
import com.bbcare.comm.DateUtil;
import com.bbcare.comm.ErrorCode;
import com.bbcare.comm.SeqUtil;
import com.bbcare.department.plat.entity.DepartmentBasic;
import com.bbcare.department.plat.entity.RandOutPatientSchedule;
import com.bbcare.department.plat.service.IDepartmentBasicService;
import com.bbcare.department.plat.store.ibatis.IAccountInfoDao;
import com.bbcare.department.plat.store.ibatis.IDeparmentBasicDao;
import com.bbcare.department.plat.store.ibatis.IOutPatientScheduleDao;
import com.bbcare.followup.plat.service.IPatientInfoHisService;
import com.bbcare.followup.plat.store.ibatis.IPatientOperationRecordDAO;

@Service
public class DepartmentBasicService implements IDepartmentBasicService {

    Logger logger = Logger.getLogger(DepartmentBasicService.class);

    @Autowired
    private IDeparmentBasicDao deparmentBasicDao;

    @Autowired
    private IAccountInfoDao accountInfoDao;

    @Autowired
    private IPatientInfoHisService patientInfoHisService;

    @Autowired
    private IPatientOperationRecordDAO patientOperationRecordDao;

    @Autowired
    private IOutPatientScheduleDao outPatientScheduleDao;

    /**
     * 查询科室基本信息主方法
     * 
     * @param arg
     * @return
     * @throws Exception
     */
    public DepartmentBasic getDepartmentBasicDetails(String deptId) throws Exception {
        logger.info("in getDepartmentBasicDetails----arg==" + deptId);
        DepartmentBasic departmentBasic = deparmentBasicDao.selectById(deptId);
        // DepartmentBasic departmentBasic = new DepartmentBasic();
        // org.apache.commons.beanutils.BeanUtils.populate(departmentBasic,
        // map);
        logger.info(JSON.toJSON(departmentBasic));
        return departmentBasic;
    }

    /**
     * 创建和更新科室基本资料
     */
    @Transactional
    public String departmentModify(DepartmentBasic departmentBasic) throws Exception {
        logger.info("in departmentModify----arg==");
        if (StringUtils.isEmpty(departmentBasic.getId())) {
            departmentBasic.setId(SeqUtil.getSeqNo());
            departmentBasic.setCreateTime(DateUtil.getSysDateA());
            deparmentBasicDao.save(departmentBasic);
        } else {
            // departmentBasic.getId();
            departmentBasic.setUpdateTime(DateUtil.getSysDateA());
            deparmentBasicDao.update(departmentBasic);
        }
        return departmentBasic.getId();
    }

    /**
     * 账户流水查询
     */
    @Override
    public List<Map<String, String>> getAccountBillsList(Map<String, Object> paramMap) {
        // TODO Auto-generated method stub
        logger.info("in getAccountBillsList");
        int page = (paramMap.get("page") != null && !StringUtils.isEmpty(paramMap.get("page").toString()))
                ? Integer.parseInt(paramMap.get("page").toString()) : 1;
        int rows = (paramMap.get("rows") != null && !StringUtils.isEmpty(paramMap.get("rows").toString()))
                ? Integer.parseInt(paramMap.get("rows").toString()) : 10;
        // Object doctorNameObject = paramMap.get("doctorName");
        // Object doctorName = (doctorNameObject!=null
        // &&!StringUtils.isEmpty(doctorNameObject)) ?
        // "%"+doctorNameObject.toString()+"%" : doctorNameObject ;

        // paramMap.put("doctorName",doctorName);
        paramMap.put("page", rows * (page - 1));
        paramMap.put("rows", rows);

        List<Map<String, String>> list = accountInfoDao.selectByCondition(paramMap);
        logger.info("out getAccountBillsList");
        return list;
    }

    /**
     * 随访排班增加接口实现
     */
    @Override
    @Transactional
    public Map<String, Object> saveRandOutPatient(Map<String, Object> paramMap) throws Exception {
        Map<String, Object> argMap = new HashMap<String, Object>(paramMap);
        Map<String, Object> outRet = new HashMap<String, Object>();

        // 权限信息
        String authorName = (String) argMap.get("authorName");
        String authorId = (String) argMap.get("authorId");
        String tenantId = (String) argMap.get("tenantId");
        int groupType = (Integer) argMap.get("groupType");
        String rootGroupId = (String) argMap.get("rootGroupId");

        // 操作信息
        String opCode = (String) argMap.get("opCode");
        String opType = (String) argMap.get("opType");
        String opNote = (String) argMap.get("opNote");
        String updateTime = (String) argMap.get("updateTime");
        String updateAccept = (String) argMap.get("updateAccept");

        // 排班业务信息
        String scheduleType = (String) argMap.get("scheduleType");
        String workDay = (String) argMap.get("workDay");
        String workPeriod = (String) argMap.get("workPeriod");

        // 校验权限（暂只支持科室排班，后续扩展）
        String scheduleId = "";
        if (Constants.TENANT_GROUP_TYPE_FOR_DEPT == groupType) {
            // 科室排班
            scheduleId = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_OUTPATIENT_SCHEDULE);// 排班id
            outRet.put("scheduleId", scheduleId);

            RandOutPatientSchedule randSchedule = new RandOutPatientSchedule();
            randSchedule.setCreateAuthor(authorId);
            randSchedule.setCreateTime(updateTime);
            randSchedule.setDeptId(rootGroupId);
            randSchedule.setId(scheduleId);
            randSchedule.setRemark("");
            randSchedule.setScheduleType(scheduleType);
            randSchedule.setTenantId(tenantId);
            randSchedule.setUpdateAccept(updateAccept);
            randSchedule.setUpdateTime(updateTime);
            randSchedule.setWorkDay(workDay);
            randSchedule.setWorkPeriod(workPeriod);

            int chkNum = outPatientScheduleDao.countRandOutPatientScheduleByUnique(randSchedule);
            if (chkNum > 0) {
                // 已添加，无法重复添加
                throw (new AppException(ErrorCode.DEPARTMENT_EXCEPTION_TYPE_DUPLICATE_OUTPATIENT_SCHEDULE, "该工作日时段排班已设置，无法重复设置!"));
            }

            outPatientScheduleDao.saveRandOutPatientSchedule(randSchedule);
        } else if (Constants.TENANT_GROUP_TYPE_FOR_HOSPITAL == groupType) {
            // 医院排班
            return outRet;
        } else if (Constants.TENANT_GROUP_TYPE_FOR_MULCENTER == groupType) {
            // 多中心排班
            return outRet;
        } else if (Constants.TENANT_GROUP_TYPE_FOR_UNION == groupType) {
            // 医联体排班
            return outRet;
        } else {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_TENANT_TYPE_UNKNOWN, "暂无匹配的租户类型，无法设置排班!"));
        }

        // 入操作流水记录表 ia_operation_record
        Map<String, Object> paramRecord = new HashMap<String, Object>();
        paramRecord.put("userName", "");
        paramRecord.put("userId", "");
        paramRecord.put("queueId", "");
        paramRecord.put("authorId", authorId);
        paramRecord.put("opTime", updateTime);
        paramRecord.put("type", Constants.DOCTOR_ACTIVE_OUT_PATIENT_SCHEDULE_BUSI_TYPE_12);
        paramRecord.put("opUsertype", Constants.OPCODE_TYPE_DOCTOR);
        paramRecord.put("authorName", authorName);
        paramRecord.put("opCode", opCode);
        paramRecord.put("updateAccept", updateAccept);
        paramRecord.put("tenantId", tenantId);
        paramRecord.put("remark", opNote);
        paramRecord.put("opType", opType);
        Map<String, Object> outRecord = patientInfoHisService.buildOperationRecord(paramRecord);
        patientOperationRecordDao.saveOperationRecord(outRecord);

        return outRet;
    }

    /**
     * 随访排班删除接口实现
     */
    @Override
    @Transactional
    public Map<String, Object> removeRandOutPatient(Map<String, Object> paramMap) throws Exception {
        Map<String, Object> argMap = new HashMap<String, Object>(paramMap);
        Map<String, Object> outRet = new HashMap<String, Object>();

        // 权限信息
        String authorName = (String) argMap.get("authorName");
        String authorId = (String) argMap.get("authorId");
        String tenantId = (String) argMap.get("tenantId");
        int groupType = (Integer) argMap.get("groupType");
        // String rootGroupId = (String) argMap.get("rootGroupId");

        // 操作信息
        String opCode = (String) argMap.get("opCode");
        String opType = (String) argMap.get("opType");
        String opNote = (String) argMap.get("opNote");
        String updateTime = (String) argMap.get("updateTime");
        String updateAccept = (String) argMap.get("updateAccept");

        // 排班业务信息
        String scheduleId = (String) argMap.get("scheduleId");

        // 校验权限（暂只支持科室排班，后续扩展）
        if (Constants.TENANT_GROUP_TYPE_FOR_DEPT == groupType) {
            // 科室排班
            Map<String, Object> randSchedule = new HashMap<String, Object>();
            randSchedule.put("id", scheduleId);
            outPatientScheduleDao.deleteRandOutPatientSchedule(randSchedule);
        } else if (Constants.TENANT_GROUP_TYPE_FOR_HOSPITAL == groupType) {
            // 医院排班
            return outRet;
        } else if (Constants.TENANT_GROUP_TYPE_FOR_MULCENTER == groupType) {
            // 多中心排班
            return outRet;
        } else if (Constants.TENANT_GROUP_TYPE_FOR_UNION == groupType) {
            // 医联体排班
            return outRet;
        } else {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_TENANT_TYPE_UNKNOWN, "暂无匹配的租户类型，无法设置排班!"));
        }

        // 入操作流水记录表 ia_operation_record
        Map<String, Object> paramRecord = new HashMap<String, Object>();
        paramRecord.put("userName", "");
        paramRecord.put("userId", "");
        paramRecord.put("queueId", "");
        paramRecord.put("authorId", authorId);
        paramRecord.put("opTime", updateTime);
        paramRecord.put("type", Constants.DOCTOR_ACTIVE_OUT_PATIENT_SCHEDULE_BUSI_TYPE_12);
        paramRecord.put("opUsertype", Constants.OPCODE_TYPE_DOCTOR);
        paramRecord.put("authorName", authorName);
        paramRecord.put("opCode", opCode);
        paramRecord.put("updateAccept", updateAccept);
        paramRecord.put("tenantId", tenantId);
        paramRecord.put("remark", opNote);
        paramRecord.put("opType", opType);
        Map<String, Object> outRecord = patientInfoHisService.buildOperationRecord(paramRecord);
        patientOperationRecordDao.saveOperationRecord(outRecord);

        return outRet;
    }

    /**
     * 随访排班查询接口实现
     */
    @Override
    @Transactional
    public Map<String, Object> listRandOutPatient(Map<String, Object> paramMap) throws Exception {
        Map<String, Object> argMap = new HashMap<String, Object>(paramMap);
        Map<String, Object> outRet = new HashMap<String, Object>();
        List<RandOutPatientSchedule> ropsList = new ArrayList<RandOutPatientSchedule>();
        outRet.put("total", 0);
        outRet.put("rows", ropsList);

        // 权限信息
        // String authorName = (String) argMap.get("authorName");
        // String authorId = (String) argMap.get("authorId");
        // String tenantId = (String) argMap.get("tenantId");
        int groupType = (Integer) argMap.get("groupType");
        String rootGroupId = (String) argMap.get("rootGroupId");

        // 校验权限（暂只支持科室排班，后续扩展）
        if (Constants.TENANT_GROUP_TYPE_FOR_DEPT == groupType) {
            // 科室排班
            Map<String, Object> randSchedule = new HashMap<String, Object>();
            randSchedule.put("deptId", rootGroupId);
            ropsList = outPatientScheduleDao.listRandOutPatientScheduleByDept(randSchedule);
        } else if (Constants.TENANT_GROUP_TYPE_FOR_HOSPITAL == groupType) {
            // 医院排班
            return outRet;
        } else if (Constants.TENANT_GROUP_TYPE_FOR_MULCENTER == groupType) {
            // 多中心排班
            return outRet;
        } else if (Constants.TENANT_GROUP_TYPE_FOR_UNION == groupType) {
            // 医联体排班
            return outRet;
        } else {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_TENANT_TYPE_UNKNOWN, "暂无匹配的租户类型，无法设置排班!"));
        }
        if (!CollectionUtils.isEmpty(ropsList)) {
            outRet.put("total", ropsList.size());
            outRet.put("rows", ropsList);
        }

        return outRet;
    }
}
